// storage/file_storage.go
package storage

import (
	"sync"

	"file-manager/models"
)

var (
	Files = make(map[string]*models.File) // in-memory file storage
	mutex = &sync.RWMutex{}               // protect concurrent access
)

// GetFile retrieves a file by ID
func GetFile(id string) (*models.File, bool) {
	mutex.RLock()
	defer mutex.RUnlock()
	file, exists := Files[id]
	return file, exists
}

// AddFile adds a new file to storage
func AddFile(file *models.File) {
	mutex.Lock()
	defer mutex.Unlock()
	Files[file.ID] = file
}

// RemoveFile removes a file from storage
func RemoveFile(id string) {
	mutex.Lock()
	defer mutex.Unlock()
	delete(Files, id)
}

// ListFilesByParent returns files in a specific parent directory
func ListFilesByParent(parent string) []*models.File {
	mutex.RLock()
	defer mutex.RUnlock()
	var result []*models.File
	for _, file := range Files {
		if file.Parent == parent {
			result = append(result, file)
		}
	}
	return result
}

// FindFileByMD5 looks for a file with matching MD5, size, and name
func FindFileByMD5(md5 string, size int64, name string) *models.File {
	mutex.RLock()
	defer mutex.RUnlock()
	for _, file := range Files {
		if file.MD5 == md5 && file.Size == size && file.Name == name {
			return file
		}
	}
	return nil
}

// FindFileByNameAndParent looks for a file/folder with matching name and parent
func FindFileByNameAndParent(name, parent string) *models.File {
	mutex.RLock()
	defer mutex.RUnlock()
	for _, file := range Files {
		if file.Name == name && file.Parent == parent {
			return file
		}
	}
	return nil
}
